package com.bluesky.jwf.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.log4j.Logger;

import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.jwf.component.Component;
import com.bluesky.jwf.component.FileField;

/**
 * unified class for enctype="multipart/form-data" or xxx-form-data
 * 
 * @author jack
 * 
 */
public class ServletContext {
	private static Logger logger = Logger.getLogger(ServletContext.class);

	private int maxSizeOfFile = 1024 * 1024 * 5;
	/**
	 * the value is either String or FileItemStream
	 */
	private Map<String, Object> parameters;
	private String encoding;

	public ServletContext(HttpServletRequest req, String encoding) {
		this.encoding = encoding;
		parameters = new HashMap<String, Object>();

		processNormalParameters(req);
		processMultipartParameters(req);
	}

	private byte[] getData(FileItemStream item) {

		try {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			int len;
			byte[] buffer = new byte[8192];
			int currentSize = 0;
			while ((len = item.openStream().read(buffer, 0, buffer.length)) != -1) {
				os.write(buffer, 0, len);
				currentSize += 8192;
				if (currentSize > maxSizeOfFile)
					throw new RuntimeException("file size exceede max size("
							+ String.valueOf(maxSizeOfFile) + ")");
			}
			return os.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private void processMultipartParameters(HttpServletRequest req) {

		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if (!isMultipart)
			return;

		try {
			ServletFileUpload upload = new ServletFileUpload();
			upload.setHeaderEncoding(encoding);

			FileItemIterator iterator = upload.getItemIterator(req);
			while (iterator.hasNext()) {

				FileItemStream item = iterator.next();

				InputStream stream = item.openStream();

				logger.info("get field:" + item.getFieldName());

				if (item.isFormField()) {
					String value = Streams.asString(stream, encoding);
					String key = item.getFieldName();
					if (parameters.containsKey(key)) {
						//concatenate values of same field
						String oldValue = (String) parameters.get(key);
						parameters.put(key, oldValue + "," + value);
					} else
						parameters.put(key, value);
				} else {
					logger.debug("Got an uploaded file: " + item.getFieldName()
							+ ", name = " + item.getName());

					FileParameter fp = new FileParameter();
					fp.setFileName(item.getName());
					fp.setContentType(item.getContentType());
					fp.setData(getData(item));
					parameters.put(item.getFieldName(), fp);

				}
			}

		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}

	private void processNormalParameters(HttpServletRequest req) {
		// then copy state from request to model
		Enumeration<String> em = req.getParameterNames();
		while (em.hasMoreElements()) {
			final String pName = em.nextElement();

			final String pValue;
			String singleValue = req.getParameter(pName);
			final String[] multipleValues = req.getParameterValues(pName);
			if (multipleValues != null && multipleValues.length > 1) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < multipleValues.length; i++) {
					if (i != 0)
						sb.append(",");

					sb.append(multipleValues[i]);
				}
				pValue = sb.toString();
			} else
				pValue = singleValue;

			parameters.put(pName, pValue);
		}
	}

	public Map<String, Object> getParameters() {
		return parameters;
	}

	public Object getParameter(String name) {
		return parameters.get(name);
	}
}
